"""
群组相关视图函数
"""
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.db.models import Q
from django.views.decorators.http import require_http_methods
from django.utils import timezone
import json

from .models import Group, GroupMembership, GroupMessage
from users.models import User
from .redis_utils import chat_redis


@login_required
@require_http_methods(["POST"])
def create_group(request):
    """创建群组"""
    try:
        data = json.loads(request.body)
        name = data.get('name', '').strip()
        description = data.get('description', '').strip()
        member_ids = data.get('member_ids', [])
        
        if not name:
            return JsonResponse({'success': False, 'message': '群组名称不能为空'})
        
        # 创建群组
        group = Group.objects.create(
            name=name,
            description=description,
            creator=request.user
        )
        
        # 添加创建者为群主
        GroupMembership.objects.create(
            group=group,
            user=request.user,
            role='owner'
        )
        
        # 添加其他成员
        for user_id in member_ids:
            try:
                user = User.objects.get(id=user_id)
                if user != request.user:
                    GroupMembership.objects.create(
                        group=group,
                        user=user,
                        role='member'
                    )
                    
                    # 发送系统消息
                    GroupMessage.objects.create(
                        group=group,
                        content=f'{user.nickname or user.username} 加入了群组',
                        message_type='system'
                    )
            except User.DoesNotExist:
                continue
        
        # 发送群组创建消息
        GroupMessage.objects.create(
            group=group,
            content=f'{request.user.nickname or request.user.username} 创建了群组',
            message_type='system'
        )
        
        return JsonResponse({
            'success': True,
            'message': '群组创建成功',
            'group': {
                'id': group.id,
                'name': group.name,
                'description': group.description,
                'avatar': group.avatar.url if group.avatar else None,
            }
        })
        
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'message': '无效的JSON数据'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})


@login_required
def get_groups_list(request):
    """获取用户加入的群组列表"""
    groups = request.user.joined_groups.all().prefetch_related('memberships')
    
    groups_data = []
    for group in groups:
        # 获取最后一条消息
        last_message = chat_redis.get_latest_message(f'group_{group.id}')
        
        if not last_message:
            db_last_message = group.get_last_message()
            if db_last_message:
                last_message = {
                    'content': db_last_message.content,
                    'created_at': db_last_message.created_at.isoformat(),
                }
        
        # 获取成员数量
        member_count = group.memberships.count()
        
        # 获取用户角色
        membership = group.memberships.filter(user=request.user).first()
        role = membership.role if membership else 'member'
        
        groups_data.append({
            'id': group.id,
            'name': group.name,
            'description': group.description,
            'avatar': group.avatar.url if group.avatar else None,
            'member_count': member_count,
            'role': role,
            'last_message': last_message,
            'created_at': group.created_at.isoformat(),
        })
    
    return JsonResponse({'success': True, 'groups': groups_data})


@login_required
def get_group_detail(request, group_id):
    """获取群组详情"""
    group = get_object_or_404(Group, id=group_id)
    
    # 检查用户是否是群成员
    membership = group.memberships.filter(user=request.user).first()
    if not membership:
        return JsonResponse({'success': False, 'message': '您不是该群组成员'})
    
    # 获取群成员列表
    members = []
    for mem in group.memberships.all().select_related('user'):
        members.append({
            'id': mem.user.id,
            'username': mem.user.username,
            'nickname': mem.user.nickname or mem.user.username,
            'avatar': mem.user.avatar.url if mem.user.avatar else None,
            'role': mem.role,
            'joined_at': mem.joined_at.isoformat(),
        })
    
    return JsonResponse({
        'success': True,
        'group': {
            'id': group.id,
            'name': group.name,
            'description': group.description,
            'avatar': group.avatar.url if group.avatar else None,
            'creator_id': group.creator.id,
            'created_at': group.created_at.isoformat(),
            'member_count': len(members),
            'members': members,
            'user_role': membership.role,
        }
    })


@login_required
def get_group_messages(request, group_id):
    """获取群组消息"""
    group = get_object_or_404(Group, id=group_id)
    
    # 检查用户是否是群成员
    if not group.memberships.filter(user=request.user).exists():
        return JsonResponse({'success': False, 'message': '您不是该群组成员'})
    
    # 从Redis获取消息
    messages_data = chat_redis.get_messages(f'group_{group_id}', limit=100)
    
    # 如果Redis中没有消息，从数据库获取并同步到Redis
    if not messages_data:
        db_messages = group.group_messages.all().order_by('created_at')
        
        for message in db_messages:
            message_data = {
                'id': message.id,
                'content': message.content,
                'sender_id': message.sender.id if message.sender else None,
                'sender_username': message.sender.username if message.sender else '系统',
                'sender_nickname': (message.sender.nickname or message.sender.username) if message.sender else '系统',
                'sender_avatar': message.sender.avatar.url if message.sender and message.sender.avatar else None,
                'created_at': message.created_at.isoformat(),
                'message_type': message.message_type,
            }
            messages_data.append(message_data)
            # 同步到Redis
            chat_redis.save_message(f'group_{group_id}', message_data)
    
    return JsonResponse({
        'success': True,
        'messages': messages_data
    })


@login_required
@require_http_methods(["POST"])
def send_group_message(request, group_id):
    """发送群组消息"""
    group = get_object_or_404(Group, id=group_id)
    
    # 检查用户是否是群成员
    if not group.memberships.filter(user=request.user).exists():
        return JsonResponse({'success': False, 'message': '您不是该群组成员'})
    
    try:
        data = json.loads(request.body)
        content = data.get('content', '').strip()
        
        if not content:
            return JsonResponse({'success': False, 'message': '消息内容不能为空'})
        
        # 创建消息
        message = GroupMessage.objects.create(
            group=group,
            sender=request.user,
            content=content,
            message_type='text'
        )
        
        # 保存消息到Redis
        message_data = {
            'id': message.id,
            'content': message.content,
            'sender_id': request.user.id,
            'sender_username': request.user.username,
            'sender_nickname': request.user.nickname or request.user.username,
            'sender_avatar': request.user.avatar.url if request.user.avatar else None,
            'created_at': message.created_at.isoformat(),
            'message_type': message.message_type,
        }
        chat_redis.save_message(f'group_{group_id}', message_data)
        
        # 更新群组时间
        group.updated_at = timezone.now()
        group.save()
        
        return JsonResponse({
            'success': True,
            'message': {
                'id': message.id,
                'content': message.content,
                'created_at': message.created_at.isoformat(),
            }
        })
        
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'message': '无效的JSON数据'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})


@login_required
@require_http_methods(["POST"])
def add_group_member(request, group_id):
    """添加群组成员"""
    group = get_object_or_404(Group, id=group_id)
    
    # 检查权限（所有群成员都可以邀请好友）
    membership = group.memberships.filter(user=request.user).first()
    if not membership:
        return JsonResponse({'success': False, 'message': '您不是该群组成员，无法邀请好友'})
    
    try:
        data = json.loads(request.body)
        user_id = data.get('user_id')
        
        user = get_object_or_404(User, id=user_id)
        
        # 检查是否已经是成员
        if group.memberships.filter(user=user).exists():
            return JsonResponse({'success': False, 'message': '该用户已经是群成员'})
        
        # 添加成员
        GroupMembership.objects.create(
            group=group,
            user=user,
            role='member'
        )
        
        # 发送系统消息
        GroupMessage.objects.create(
            group=group,
            content=f'{user.nickname or user.username} 加入了群组',
            message_type='system'
        )
        
        # 通过WebSocket通知所有群成员
        from channels.layers import get_channel_layer
        from asgiref.sync import async_to_sync
        
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            f'group_chat_{group_id}',
            {
                'type': 'group_update',
                'update': {
                    'type': 'member_added',
                    'user': {
                        'id': user.id,
                        'nickname': user.nickname or user.username,
                    }
                }
            }
        )
        
        return JsonResponse({'success': True, 'message': '成员添加成功'})
        
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'message': '无效的JSON数据'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})


@login_required
@require_http_methods(["POST"])
def remove_group_member(request, group_id, user_id):
    """移除群组成员"""
    group = get_object_or_404(Group, id=group_id)
    
    # 检查权限（只有群主可以踢出成员）
    membership = group.memberships.filter(user=request.user).first()
    if not membership or membership.role != 'owner':
        return JsonResponse({'success': False, 'message': '只有群主可以踢出成员'})
    
    user = get_object_or_404(User, id=user_id)
    
    # 不能移除群主
    target_membership = group.memberships.filter(user=user).first()
    if not target_membership:
        return JsonResponse({'success': False, 'message': '该用户不是群成员'})
    
    if target_membership.role == 'owner':
        return JsonResponse({'success': False, 'message': '不能移除群主'})
    
    # 移除成员
    target_membership.delete()
    
    # 发送系统消息
    GroupMessage.objects.create(
        group=group,
        content=f'{user.nickname or user.username} 被移出了群组',
        message_type='system'
    )
    
    # 通过WebSocket通知所有群成员
    from channels.layers import get_channel_layer
    from asgiref.sync import async_to_sync
    
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        f'group_chat_{group_id}',
        {
            'type': 'group_update',
            'update': {
                'type': 'member_removed',
                'user': {
                    'id': user.id,
                    'nickname': user.nickname or user.username,
                }
            }
        }
    )
    
    return JsonResponse({'success': True, 'message': '成员已移除'})


@login_required
@require_http_methods(["POST"])
def leave_group(request, group_id):
    """退出群组"""
    group = get_object_or_404(Group, id=group_id)
    
    membership = group.memberships.filter(user=request.user).first()
    if not membership:
        return JsonResponse({'success': False, 'message': '您不是该群组成员'})
    
    # 群主不能直接退出，需要先转让群主
    if membership.role == 'owner':
        return JsonResponse({'success': False, 'message': '群主不能直接退出，请先转让群主'})
    
    # 退出群组
    membership.delete()
    
    # 发送系统消息
    GroupMessage.objects.create(
        group=group,
        content=f'{request.user.nickname or request.user.username} 离开了群组',
        message_type='system'
    )
    
    return JsonResponse({'success': True, 'message': '已退出群组'})


@login_required
@require_http_methods(["POST"])
def update_group(request, group_id):
    """更新群组信息（仅群主可操作）"""
    group = get_object_or_404(Group, id=group_id)
    
    # 检查权限（只有群主可以修改）
    membership = group.memberships.filter(user=request.user).first()
    if not membership or membership.role != 'owner':
        return JsonResponse({'success': False, 'message': '只有群主可以修改群组信息'})
    
    try:
        data = json.loads(request.body)
        name = data.get('name', '').strip()
        description = data.get('description', '').strip()
        
        if name:
            group.name = name
        if description is not None:
            group.description = description
        
        group.save()
        
        # 通过WebSocket通知所有群成员
        from channels.layers import get_channel_layer
        from asgiref.sync import async_to_sync
        
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            f'group_chat_{group_id}',
            {
                'type': 'group_update',
                'update': {
                    'type': 'info_updated',
                    'group': {
                        'id': group.id,
                        'name': group.name,
                        'description': group.description,
                        'avatar': group.avatar.url if group.avatar else None,
                    }
                }
            }
        )
        
        return JsonResponse({
            'success': True,
            'message': '群组信息已更新',
            'group': {
                'id': group.id,
                'name': group.name,
                'description': group.description,
                'avatar': group.avatar.url if group.avatar else None,
            }
        })
        
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'message': '无效的JSON数据'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})


@login_required
@require_http_methods(["POST"])
def update_group_avatar(request, group_id):
    """更新群组头像（仅群主可操作）"""
    group = get_object_or_404(Group, id=group_id)
    
    # 检查权限（只有群主可以修改）
    membership = group.memberships.filter(user=request.user).first()
    if not membership or membership.role != 'owner':
        return JsonResponse({'success': False, 'message': '只有群主可以修改群组头像'})
    
    if 'avatar' not in request.FILES:
        return JsonResponse({'success': False, 'message': '请上传头像文件'})
    
    group.avatar = request.FILES['avatar']
    group.save()
    
    # 通过WebSocket通知所有群成员
    from channels.layers import get_channel_layer
    from asgiref.sync import async_to_sync
    
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        f'group_chat_{group_id}',
        {
            'type': 'group_update',
            'update': {
                'type': 'avatar_updated',
                'group': {
                    'id': group.id,
                    'avatar': group.avatar.url,
                }
            }
        }
    )
    
    return JsonResponse({
        'success': True,
        'message': '群组头像已更新',
        'avatar_url': group.avatar.url
    })


@login_required
@require_http_methods(["POST"])
def dissolve_group(request, group_id):
    """解散群组（仅群主可操作）"""
    group = get_object_or_404(Group, id=group_id)
    
    # 检查权限（只有群主可以解散群组）
    membership = group.memberships.filter(user=request.user).first()
    if not membership or membership.role != 'owner':
        return JsonResponse({'success': False, 'message': '只有群主可以解散群组'})
    
    try:
        # 通过WebSocket通知所有群成员群组即将解散
        from channels.layers import get_channel_layer
        from asgiref.sync import async_to_sync
        
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            f'group_chat_{group_id}',
            {
                'type': 'group_update',
                'update': {
                    'type': 'group_dissolved',
                    'message': f'群组 "{group.name}" 已被群主解散'
                }
            }
        )
        
        # 删除群组（会级联删除所有相关数据）
        group_name = group.name
        group.delete()
        
        return JsonResponse({
            'success': True,
            'message': f'群组 "{group_name}" 已解散'
        })
        
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'解散群组失败: {str(e)}'})
